import storage from '@/utils/storage';
import { LoadingOutlined, PlusOutlined } from '@ant-design/icons';
import { Modal, Form, Input, Select, Upload, TreeSelect } from 'antd';
import {
  RcFile,
  UploadChangeParam,
  UploadFile,
  UploadProps
} from 'antd/es/upload';
import { useEffect, useImperativeHandle, useState } from 'react';
import { message } from '@/utils/AntdGlobal';
import { IAction, IModalProps } from '@/types/modal';
import { User, Dept, Role } from '@/types';
import { createUser, editorUser, getDeptList, getAllRoleList } from '@/api';

export default function CreateUser(props: IModalProps) {
  const [form] = Form.useForm();
  const [img, setImg] = useState('');
  const [loading, setLoading] = useState(false);
  const [visiable, setVisiable] = useState(false);
  const [action, setAction] = useState<IAction>('create');
  const [deptList, setDeptList] = useState<Dept.DeptItem[]>();
  const [deptValue, setDeptValue] = useState<string>('');
  const [allRoleList, setAllRoleList] = useState<Role.RoleItem[]>();

  useEffect(() => {
    getDeptListData();
    getAllRoleListData();
  }, []);

  useImperativeHandle(props.mRef, () => {
    return {
      open
    };
  });

  // 调用弹框显示方法
  const open = (type: IAction, data?: User.UserItem) => {
    setVisiable(true);
    setAction(type);
    if (type === 'edit' && data) {
      form.setFieldsValue(data);
    }
  };
  const handleSubmit = async () => {
    const valide = await form.validateFields();
    if (valide) {
      const params = {
        ...form.getFieldsValue(),
        userImg: img
      };
      if (action === 'create') {
        try {
          await createUser(params);
          message.success('添加成功');
        } catch (err) {
          console.log(err);
        }
      }
      if (action === 'edit') {
        try {
          await editorUser(params);
          message.success('编辑成功');
        } catch (err) {
          console.log(err);
        }
      }
      handleCancel();
      props.update();
    }
  };
  const handleCancel = () => {
    setVisiable(false);
    form.resetFields();
  };
  // 上传之前
  const beforeUpload = (fill: RcFile) => {
    const isJpgOrPng = fill.type === 'image/jpeg' || fill.type === 'image/png';
    if (!isJpgOrPng) {
      message.error('你只能上传JPG/PNG格式的图片!');
    }
    const isLt2M = fill.size / 1024 / 1024 < 0.5;
    console.log(fill.size / 1024 / 1024);
    if (!isLt2M) {
      message.error('上传图片必须小于500k');
    }
    return isJpgOrPng && isLt2M;
  };
  // 上传后图片处理
  const handleChange: UploadProps['onChange'] = (
    info: UploadChangeParam<UploadFile>
  ) => {
    if (info.file.status === 'uploading') {
      setLoading(true);
    }
    if (info.file.status === 'done') {
      setLoading(false);
      const { code, data, msg } = info.file.response;
      if (code === 0) {
        setImg(data.file);
      } else {
        message.error(msg);
      }
    } else if (info.file.status === 'error') {
      message.error('服务器异常，请稍后重试！');
    }
  };
  const getDeptListData = async () => {
    const deptList = await getDeptList();
    setDeptList(deptList);
  };
  const getAllRoleListData = async () => {
    const allRoleList = await getAllRoleList();
    setAllRoleList(allRoleList);
  };
  const onChange = (newValue: string) => {
    setDeptValue(newValue);
  };
  const handleSelectedRole = () => {};
  return (
    <Modal
      title={action === 'create' ? '创建用户' : '编辑用户'}
      width={800}
      open={visiable}
      onOk={handleSubmit}
      onCancel={handleCancel}
    >
      <Form labelCol={{ span: 4 }} labelAlign='right' form={form}>
        <Form.Item label='用户Id' name='userId' style={{ display: 'none' }}>
          <Input></Input>
        </Form.Item>
        <Form.Item
          label='用户名称'
          name='userName'
          rules={[
            {
              required: true,
              message: '请输入用户名称'
            },
            {
              min: 1,
              max: 12,
              message: '用户名称长度为1-12个字符'
            }
          ]}
        >
          <Input placeholder='请输入用户名称'></Input>
        </Form.Item>
        <Form.Item
          label='用户邮箱'
          name='userEmail'
          rules={[
            {
              required: true,
              message: '请输入用户邮箱'
            },
            {
              type: 'email',
              message: '请输入正确的邮箱地址'
            }
          ]}
        >
          <Input
            placeholder='请输入用户邮箱'
            disabled={action === 'edit' ? true : false}
          ></Input>
        </Form.Item>
        <Form.Item
          label='手机号'
          name='mobile'
          rules={[
            {
              len: 11,
              message: '请输入11位手机号'
            },
            {
              pattern: /1[1-9]\d{9}/,
              message: '请输入1开发的11位手机号'
            }
          ]}
        >
          <Input placeholder='请输入手机号' type='number'></Input>
        </Form.Item>
        <Form.Item
          label='部门'
          name='deptId'
          rules={[
            {
              required: true,
              message: '请选择部门'
            }
          ]}
        >
          <TreeSelect
            showSearch
            style={{ width: '100%' }}
            value={deptValue}
            dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
            placeholder='请选择部门'
            allowClear
            treeDefaultExpandAll
            onChange={onChange}
            treeData={deptList}
            fieldNames={{
              label: 'deptName',
              children: 'children',
              value: '_id'
            }}
          />
        </Form.Item>
        <Form.Item label='岗位' name='job'>
          <Input placeholder='请输入岗位'></Input>
        </Form.Item>
        <Form.Item label='状态' name='state'>
          <Select>
            <Select.Option value={1}>在职</Select.Option>
            <Select.Option value={2}>离职</Select.Option>
            <Select.Option value={3}>试用期</Select.Option>
          </Select>
        </Form.Item>
        <Form.Item label='系统角色' name='roleList'>
          <Select
            showSearch
            placeholder='Select a person'
            optionFilterProp='children'
            onChange={handleSelectedRole}
            options={allRoleList}
            fieldNames={{
              label: 'roleName',
              value: '_id'
            }}
          />
        </Form.Item>
        <Form.Item label='用户头像'>
          <Upload
            listType='picture-circle'
            showUploadList={false}
            headers={{
              Authorization: `Bearer ${storage.get('token')} `,
              icode: '7888DCA69B8C1D60'
            }}
            action='/api/users/upload'
            beforeUpload={beforeUpload}
            onChange={handleChange}
          >
            {img ? (
              <img src={img} alt='头像' style={{ width: '100%' }}></img>
            ) : (
              <div>
                {loading ? (
                  <LoadingOutlined></LoadingOutlined>
                ) : (
                  <PlusOutlined></PlusOutlined>
                )}
                <div style={{ marginTop: 5 }}>上传头像</div>
              </div>
            )}
          </Upload>
        </Form.Item>
      </Form>
    </Modal>
  );
}
